<script setup lang="ts">
import { tableConfig } from './config/table-config';
import { formConfig } from './config/form-config';
import baseTable from '@/components/base-ui/base-table/index.vue';
import { doGetBomDetail } from '@/api/modeling/bom/index';
import { transformDataToKeys, flattenArray } from '@/utils';
import { generateNameToLevel } from '@/config/constant';
import type { BomItemDTO, BomDataRequest } from '@/api/modeling/bom/model/type';

interface BomForm {
    [key: string]: string | null;
    materialCode: string | null;
    materialName: string | null;
    bomCode: string | null;
    bomName: string | null;
}

const initBomForm = () => {
    return {
        materialCode: null,
        materialName: null,
        bomName: null,
        bomCode: null
    };
};

const bomForm = ref<BomForm>(initBomForm());
const formItems = ref<ItemConfig[]>(formConfig.items);
const tableData = ref();

/**
 * @: 新增提交
 * @param {*} const
 * @return {*}
 */
const {
    visible,
    handleFullscreen,
    getMaxHeight,
    modalSlotRef: tableRef
} = useModal({
    data: { bomForm, tableData }
});
const open = (id: string) => {
    visible.value = true;
    initData(id!);
};

/**
 * 编辑状态，初始化数据
 */
const initData = async (id: string) => {
    try {
        const { data } = await doGetBomDetail({ id }); // 获取 BOM 详情
        if (data) {
            handleInitEditData(data as unknown as BomDataRequest);
        }
    } catch (error) {
        console.error(error);
    }
};

/**
 * 处理编辑初始化数据
 */
const BomDetailId = ref();
const bomCodeDisabled = ref(false);
const handleInitEditData = (data: BomDataRequest) => {
    BomDetailId.value = data.id; // BOM id
    tableRef.value.setInit(false); // 取消默认表格添加行
    bomCodeDisabled.value = true;

    bomForm.value = {
        ...transformDataToKeys<any>(data, ['bomCode', 'bomName', 'materialCode', 'materialName'])
    };

    const newTableData = transformEditTableData(data.children);
    tableRef.value.setTableData(newTableData);
    tableData.value = newTableData; // 表单提交的时候使用该变量

    nextTick(() => {
        setAsyncColumnWidth();
    });
};

/**
 * 递归遍历表格数据，更新字段值
 */
const transformEditTableData = (arr: BomItemDTO[]) => {
    return arr.map(function (obj) {
        obj.unAction = true;
        obj.edit = true;
        if (obj.children && obj.children.length > 0) {
            obj.children = transformEditTableData(obj.children);
        }
        return obj;
    });
};

/**
 * 动态设置列宽
 * @return {*}
 */
let currentLevel = 0;
const levelColumn = tableConfig.items.filter(item => item.modelKey === 'level');
const initColumnWidth = levelColumn[0].columnProps?.width as string;
const setAsyncColumnWidth = () => {
    const flatternTableData = flattenArray(tableData.value);
    const maxLevel = Math.max(...flatternTableData.map(item => item.level));
    const maxLevelEdge = 6; // 层级最大临界点

    // 超过规定的最大临界点且当前最大层级与当前设置层级不相等
    if (maxLevel > maxLevelEdge && maxLevel !== currentLevel) {
        currentLevel = maxLevel;
        // 动态设置表头宽度
        tableRef.value.setAsyncColumnWidth(
            'level',
            parseInt(initColumnWidth) + 30 * (maxLevel - maxLevelEdge) // 初始宽 + 递增宽范围 x (最大层级 - 层级最大临界点)
        );
    }
};

const handleOk = () => {
    visible.value = false;
};

defineExpose({
    open
});
</script>
<template>
    <q-modal
        v-model:visible="visible"
        :fullscreen="true"
        title="查看"
        width="1000px"
        :style="{ top: '30px' }"
        :hide-cancel-btn="true"
        ok-text="关闭"
        @ok="handleOk"
        @fullscreen="handleFullscreen"
    >
        <div :id="generateNameToLevel('4')">
            <q-form-item :id="formConfig.id!" class="form-placeholder"></q-form-item>
            <el-row :gutter="32" class="m-b-24">
                <el-col
                    v-for="item in formItems"
                    :key="item.validProps?.id"
                    :span="12"
                    class="role-main__header form-common m-b-18"
                >
                    <label class="is-column"><span>*</span>{{ item.columnProps?.label }}:</label>
                    <q-form-item
                        v-if="!item.itemType || item.itemType === 'text'"
                        :id="item.validProps?.id!"
                    >
                        <el-input
                            v-model="bomForm[item.modelKey!]"
                            :placeholder="`请输入${item.columnProps?.label}`"
                            disabled
                            v-bind="item.elInputProps"
                        />
                    </q-form-item>
                    <q-form-item v-else-if="item.itemType === 'other'" :id="item.validProps?.id!">
                        <q-virtual-select
                            v-model="bomForm[item.modelKey!]"
                            placeholder="请选择物料编码"
                            disabled
                        />
                    </q-form-item>
                </el-col>
            </el-row>
            <base-table
                ref="tableRef"
                :max-height="getMaxHeight"
                :modal-mode="true"
                :hide-del="true"
                :close-edit="true"
                :closeDelRow="true"
                :max-add-num="10"
                action-width="180px"
                add-tip="每个BOM层级单次最多添加10行数据"
                :table-config="tableConfig"
                :table-attr="{
                    treeProps: { children: 'children' },
                    defaultExpandAll: true
                }"
                add-table-row
            >
                <!-- 序号 -->
                <template #index>
                    <el-table-column type="index" label="序号" width="55">
                        <template #default="{ $index }"
                            ><span :style="{ color: '#bfbfbf' }">{{ $index + 1 }}</span></template
                        >
                    </el-table-column>
                </template>
                <!-- BOM 层级 -->
                <template #level="{ row }">
                    <span>{{ row.level || '--' }}</span>
                </template>
                <!-- 子项物料编码 -->
                <template #materialCode="{ row }">
                    <q-virtual-select v-model="row.materialCode" disabled placeholder="请选择" />
                </template>

                <!-- 子项物料名称 -->
                <template #materialName="{ row }">
                    {{ row.materialName || '--' }}
                </template>

                <!-- 生产类型 -->
                <template #productionType="{ row }">
                    {{ row.productionType || '--' }}
                </template>

                <!-- 规格型号 -->
                <template #materialSpecification="{ row }">
                    {{ row.materialSpecification || '--' }}
                </template>

                <!-- 单位 -->
                <template #unit="{ row }">
                    {{ row.unit || '--' }}
                </template>
            </base-table>
        </div>
    </q-modal>
</template>

<style lang="scss" scoped>
@include b(m-action) {
    @include e(btn) {
        margin-left: 12px;

        &:nth-of-type(1) {
            margin-left: 0;
        }
    }
}
</style>
